package com.microstream.user;

import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.io.*; 

import javax.jdo.PersistenceManager;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.microstream.lift.guestbook.Greeting;
import com.microstream.lift.guestbook.PMF;

import com.microstream.dao.MsUser;
import com.microstream.global.*;

public class UserLoginServlet extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	public void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		
		String loginUser = "";    //UserUtility.getLoginUserFromSession(req.getSession(true));		
		String userPassword = ""; 
		
		loginUser = req.getParameter("user_name").toString(); 
		userPassword = req.getParameter("user_password").toString(); 
		
		if(loginUser.equals("")) {
			resp.sendRedirect("/error.jsp");			
		}
				
		PersistenceManager pm = PMF.get().getPersistenceManager();
		String query = "select from " 
			 + MsUser.class.getName() 
			 + " where userName == '" + loginUser + "'"
			 + " && userPassword == '" + userPassword + "'"; 
			 		
		List<MsUser> users = (List<MsUser>) pm.newQuery(query).execute();
	
		HttpSession session = req.getSession(true);
		
		if( users.size() >= 1 ) {			
			 
			session.setAttribute(GlobalConstant.SESSION_USER_LOGIN_NAME, loginUser );
			resp.sendRedirect("/");		
			
		}
		else {
			resp.sendRedirect("/error.jsp");			
		}
	}

}
